package com.cd.music.exception;

import com.cd.music.utils.ServletUtil;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author yxl 余秀良
 * @version 1.0
 * @description: 控制器异常注解实现类
 * @date 2017年10月25日 上午10:59
 * @address: 四川成都
 */
@ControllerAdvice
public class ControllerException {
    private static final Logger logger = Logger.getLogger(ControllerException.class);

    @ExceptionHandler(value = Exception.class)
    public void execute(HttpServletResponse response, Exception e) {
        try {
            // 根据不同的异常类型进行不同处理
            if (e instanceof SQLException) {
                ServletUtil.returnJson(response, null, "数据库异常" + e.getMessage(), false, 500);
            } else if (e instanceof IOException) {
                ServletUtil.returnJson(response, null, "IO异常" + e.getMessage(), false, 500);
            } else if (e instanceof NullPointerException) {
                ServletUtil.returnJson(response, null, "空指针异常" + e.getMessage(), false, 500);
            } else if (e instanceof RuntimeException) {
                response.setStatus(423);
                ServletUtil.returnJson(response, null, e.getMessage(), false, 423);
            } else {
                ServletUtil.returnJson(response, null, e.getMessage(), false, 423);
            }
        } catch (Exception ex) {
            logger.error("ExceptionImpl类的execute方法发生异常: " + ex.getMessage());
        }
    }
}
